
/**
 * 断言工具类
 * @author Zhang, BS
 */
export abstract class Assert {
  /**
   * 给定一个表达式, 表达式结果为false抛出异常
   * @param expression
   * @param msg
   */
  static state(expression: boolean, msg: string): asserts expression {
    if (!expression) {
      throw new Error(msg);
    }
  }

  /**
   * 对象不为空
   * @param o
   * @param msg
   * @throws Error
   */
  static notNull<T>(o: T, msg: string): asserts o is NonNullable<T> {
    if (o == null) {
      throw new Error(msg);
    }
  }

  /**
   * 对象不为空,字符串不为空字符串,Array/Set/Map中的元素数量大于0
   * @param o
   * @param msg
   */
  static notEmpty(o: object | string | Array<any> | Set<any> | Map<any, any>, msg: string): asserts o {
    if (
      o == null ||
      o === '' ||
      (o instanceof Array && o.length === 0) ||
      (o instanceof Set && o.size === 0) ||
      (o instanceof Map && o.size === 0)
    ) {
      throw new Error(msg);
    }
  }

  /**
   * 不为空白字符串
   * @param o
   * @param msg
   */
  static notBlank(o: any, msg: string): asserts o is string {
    if (o == null || o.toString().trim().length === 0) {
      throw new Error(msg);
    }
  }

  /**
   * 两个值相等
   * @param actual
   * @param excepted
   * @param msg
   */
  static equals<T>(actual: any, excepted: T, msg: string): asserts actual is T {
    if (actual !== excepted) {
      throw new Error(msg);
    }
  }

  /**
   * 是一个有效的日期对象
   * @param date
   * @param msg
   */
  static isValidDate(date: Date, msg: string): asserts date is Date {
    if (date == null || date.toString() === 'Invalid Date') {
      throw new Error(msg);
    }
  }
}
